<template>
	<view class="page" :initdata="initdata" :change:initdata="ether.getalldata" :approvestatus="approvestatus"
		:change:approvestatus="ether.shouquanover" :extractstatus="extractstatus" :change:extractstatus="ether.extract"
		:lpnum="lpnum" :change:lpnum="ether.changelpnum" :implementid="implementid"
		:change:implementid="ether.implement">
		<HeaderBar title="添加流动性" showBack backgroundColor="#F6F6F6" fixed />
		<view class="bigblock">
			<view class="block1" v-for="(item,index) in pairs">
				<view class="line3">
					<view class="left">
						<view class="images">
							<image class="image1"
								src="/static/images/tokenicon/0x0000000000000000000000000000000000000000ETH5867.png"
								mode="widthFix"></image>
							<image class="image2"
								:src="'../../static/images/tokenicon/'+item.contract+initdata.addressInfo.chainType+initdata.addressInfo.chainId+'.png'"
								mode="widthFix">
							</image>
						</view>
						<view class="lines">
							<view class="smallline1">
								JUMP-{{item.tokenname}}
							</view>
							<view class="smallline2">
								质押LP获得更多奖励
							</view>
						</view>
					</view>
				</view>
				<view class="line4">
					<view class="smallline1">
						<view class="text1">
							我的LP
						</view>
						<view class="text2">
							{{ Number(Number(item.mylp).toFixed(4))}}
							<text class="smalltext">LP</text>
						</view>
					</view>
					<view class="smallline1">
						<view class="text1">
							流动性JUMP
						</view>
						<view class="text2">
							{{ Number(Number(item.ethnum).toFixed(4)) }}
							<text class="smalltext">HEC</text>
						</view>
					</view>
					<view class="smallline1">
						<view class="text1">
							流动性{{item.tokenname}}
						</view>
						<view class="text2">
							{{ Number(Number(item.tokennum).toFixed(4)) }}
							<text class="smalltext">{{item.tokenname}} </text>
						</view>
					</view>
					<view class="smallline1">
						<view class="text1">
							流动性代币总数
						</view>
						<view class="text2">
							{{ Number(Number(item.alllp).toFixed(4)) }}
							<text class="smalltext">LP</text>
						</view>
					</view>
					<view class="smallline1">
						<view class="text1">
							LP合约地址
						</view>
						<view class="text2" style="margin-top:20upx;word-break:break-all;">
							{{item.pairaddress}}
						</view>
					</view>
				</view>
				<view class="line6">
					<view class="button" :data-selectpairaddress="item.pairaddress" :data-selectcontract="item.contract"
						:data-yue="item.mylp" @tap="ether.openextract1">
						移除流动性
					</view>
				</view>
			</view>
			<view v-if="pairs.length==0">
				<zanwei style="margin-top:400upx;" type="2"></zanwei>
			</view>
		</view>
		<!-- 移除弹窗 -->
		<uni-popup ref="popup1">
			<view class="block2">
				<view class="line1">
					移除流动性
				</view>
				<view class="line2">
					<uni-easyinput class="input" type="number" v-model="lpnum" placeholder="请输入数量" />
					<text class="text1" @tap="all">全部</text>
				</view>
				<view class="line3">
					<view class="text1" @tap="closeextract()">
						取消
					</view>
					<view class="text2" @tap="changeextractstatus(true)">
						确定
					</view>
				</view>
			</view>
		</uni-popup>
		<!-- 代币授权弹窗 -->
		<uni-popup ref="popup2">
			<view class="block3">
				<view class="title">
					授权额度
				</view>
				<view class="line3">
					<text class="tip">*</text>移除流动性需要对代币进行授权，授权成功后请重新操作。
				</view>
				<view class="line4">
					<view class="button button1" @tap="approveclose">
						取消
					</view>
					<view class="button button2" @tap='changeapprovestatus(true)'>
						确定
					</view>
				</view>
			</view>
		</uni-popup>
		<!-- 底部确认弹窗 -->
		<uni-popup ref="popup4" type="bottom" background-color="#FFFFFF" border-radius="10px 10px 0 0">
			<view class="popupTitle">
				交易详情
			</view>
			<view class="numberBox">
				<view class="number">
					<text v-if="implementinfo.methond=='approve'">申请代币{{implementinfo.symbol}}转账授权</text>
					<text v-else>{{Number(Number(implementinfo.value).toFixed(4))}}JUMP</text>
				</view>
			</view>

			<view class="fromAddress">
				<view class="left">
					收款地址
				</view>
				<view class="right">
					<view class="address">
						{{implementinfo.to}}
					</view>
					<!-- <text class="chain">123123</text> -->
				</view>
			</view>
			<view class="toAddress">
				<view class="left">
					付款地址
				</view>
				<view class="right">
					<view class="address">
						{{implementinfo.from}}
					</view>
				</view>
			</view>
			<view class="toAddress">
				<view class="left">
					网络费
				</view>
				<view class="right">
					<view class="address">
						{{implementinfo.fee}}JUMP
					</view>
					<text class="chain">=Gas Limit({{implementinfo.gasLimit}})*Gas
						Price({{Number(Number(implementinfo.gasPrice).toFixed(4))}}
						gwei)</text>
				</view>
			</view>

			<view class="popupBtn">
				<view class="pbtn quxiaopth" @tap="cancel">
					取消
				</view>
				<view class="pbtn" @tap="determine">
					确定
				</view>
			</view>
		</uni-popup>
		<!-- 密码弹窗 -->
		<PasswordPopup ref="passwordPopup" @close="passwordclose" @confirm="implement" />
	</view>
</template>
<script>
	import {
		getSwapCoin
	} from '@/http/api.js';
	import common from '@/js_sdk/common/common.js'
	export default {
		data() {
			return {
				// 交易对信息
				pairs: [],
				// 输入的lp数量
				lpnum: "",
				// 当前选中的交易对
				selectpairaddress: "",
				// 当前选中的代币地址
				selectcontract: "",
				// 当前选中的交易对LP代币数量
				yue: "",
				// 移除交易对方法状态
				extractstatus: false,
				// 授权方法状态
				approvestatus: false,
				// 执行信息确认
				implementinfo: null,
				// 执行的id
				implementid: null
			}
		},
		computed: {
			initdata() {
				return {
					addressInfo: this.$store.getters.addressInfo,
					selectedRpc: this.$store.getters.getRpc,
					config: common.config,
					tokens: []
				}
			}
		},
		onLoad() {
			this.getSwapCoin()
		},
		methods: {
			...common.methonds,
			// 获取允许兑换的代币
			async getSwapCoin() {


				let params = {
					chain: "5867"
				}
				let res = await getSwapCoin(params);
				let tokenlist = res.data
				let jumpindex;
				tokenlist.forEach(function(item, index) {
					if (item.name == "JUMP") {
						jumpindex = index
					}
				})
				tokenlist.splice(jumpindex, 1)
				this.initdata.tokens = tokenlist
			},
			// 获取所有的交易对信息
			getpairs(pairs) {
				this.pairs = pairs
				uni.hideLoading()
			},
			// 打开提取流动性弹窗
			// 因为有些数据需要rendjs层来用，所以这个方法是有rendjs曾来调用的
			async openextract2(yue) {
				this.yue = yue
				this.$refs.popup1.open("center")
			},
			// 全部代币数量
			all() {
				this.lpnum = this.yue
			},
			// 关闭移除流动性弹窗
			closeextract() {
				this.lpnum = ""
				this.$refs.popup1.close()
			},
			// 修改移除流动性事件状态
			changeextractstatus(status) {
				if (this.lpnum == "") {
					return this.error("请输入移除数量")
				}
				if (Number(this.lpnum) > Number(this.yue)) {
					return this.error("余额不足")
				}
				this.$refs.popup1.close()
				this.extractstatus = status
			},
			// 修改移除流动性事件状态，rendjs调用
			changeextractstatus2(status) {
				this.$refs.popup1.close()
				this.lpnum = ""
				this.extractstatus = status
			},
			// 打开代币授权弹窗
			openapprovewindow() {
				this.$refs.popup2.open('center')
			},
			// 修改授权事件状态
			changeapprovestatus(status) {
				this.approvestatus = status
			},
			// 关闭代币授权弹窗
			approveclose() {
				this.$refs.popup2.close()
			},
			// 打开确认执行弹窗
			openimplement(data) {
				this.implementinfo = data
				this.$refs.popup2.close()
				this.$refs.popup4.open()
			},
			// 取消执行
			cancel() {
				this.$refs.popup4.close()
			},
			// 确认执行，打开密码弹窗
			determine() {
				this.$refs.passwordPopup.open()
			},
			// 密码弹窗点击确认
			implement() {
				this.implementid = this.implementinfo.id
				this.cancel()
				this.passwordclose()
			},
			// 关闭密码弹窗
			passwordclose() {
				this.$refs.passwordPopup.close()
			}
		}
	}
</script>
<script module="ether" lang="renderjs">
	export default {
		data() {
			return {
				initdata: {},
				jsstatus: false,
				datastatus: false,
				selectpairaddress: "",
				selectcontract: "",
				lpnum: "",
			}
		},
		mounted() {
			// 动态引入较大类库避免影响页面展示
			let script = document.createElement('script')
			script.src = 'static/script/ethers-5.2.umd.min.js'
			document.head.appendChild(script)
			script.onload = this.changjsstatus
		},
		methods: {
			// js同步
			changjsstatus() {
				this.jsstatus = true
				if (this.datastatus == true) {
					this.getliquidity()
				}
			},
			// 同步数据
			getalldata(newValue) {
				if (newValue) {
					this.initdata = newValue
					this.datastatus = true
					if (this.jsstatus == true) {
						this.getliquidity()
					}
				}
			},
			// 获取pair地址的相关信息
			async getliquidity() {
				this.$ownerInstance.callMethod('showloading')
				try {
					let provider = new ethers.providers.JsonRpcProvider(this.initdata.selectedRpc);
					let signer = new ethers.Wallet(this.initdata.addressInfo.privateKey, provider);
					let address = signer.address
					let factorycontract = new ethers.Contract(this.initdata.config.swapfactory, this.initdata
						.config.factoryabi,
						signer);
					let pairs = []
					for (let i = 0; i < this.initdata.tokens.length; i++) {
						let factorydata = await factorycontract.getPair(this.initdata.config.weth, this.initdata
							.tokens[i]
							.contract)
						let paircontract = new ethers.Contract(factorydata, this.initdata.config.pairabi, signer);
						let pairdata = await paircontract.getReserves()
						// 获取池子里两个代币的余额
						let token0 = await paircontract.token0()
						let token1 = await paircontract.token1()
						let ethnum, tokennum;
						if (token0 == this.initdata.config.weth) {
							ethnum = ethers.utils.formatUnits(pairdata.reserve0.toString(), '18')
							tokennum = ethers.utils.formatUnits(pairdata.reserve1.toString(), this.initdata.tokens[i]
								.decimal)
						} else {
							ethnum = ethers.utils.formatUnits(pairdata.reserve0.toString(), this.initdata.tokens[i]
								.decimal)
							tokennum = ethers.utils.formatUnits(pairdata.reserve1.toString(), '18')
						}

						let erc20contract = new ethers.Contract(factorydata, this.initdata.config.erc20abi, signer);
						let bignum = await erc20contract.balanceOf(address)
						let decimal = await erc20contract.decimals()
						let mylp = ethers.utils.formatUnits(bignum.toString(), decimal)

						let erc20data2 = await erc20contract.totalSupply()
						let alllp = ethers.utils.formatUnits(erc20data2.toString(), decimal)
						let item = {
							token0,
							token1,
							ethnum,
							tokennum,
							mylp,
							alllp,
							pairaddress: factorydata,
							tokenname: this.initdata.tokens[i].name,
							contract: this.initdata.tokens[i].contract
						}
						if (Number(item.mylp) > 0) {
							pairs.push(item)
						}
					}
					this.$ownerInstance.callMethod('getpairs', pairs)

				} catch (e) {
					this.$ownerInstance.callMethod('error', "合约执行失败")
				}
				this.$ownerInstance.callMethod('hideloading')

			},
			// 打开提取弹窗之前，把接下来的方法要用到的数据同步到下面
			// 然后在通过事件让逻辑层打开弹窗
			openextract1(e) {
				this.selectpairaddress = e.currentTarget.dataset.selectpairaddress
				this.selectcontract = e.currentTarget.dataset.selectcontract
				this.yue = e.currentTarget.dataset.yue
				this.$ownerInstance.callMethod('openextract2', e.currentTarget.dataset.yue)
			},
			// 同步输入提取数量的方法
			changelpnum(newValue) {
				if (newValue) {
					this.lpnum = newValue
				}
			},
			async extract(newValue) {

				if (newValue) {
					this.$ownerInstance.callMethod('showloading')
					try {
						this.$ownerInstance.callMethod('changeextractstatus2', false)
						let provider = new ethers.providers.JsonRpcProvider(this.initdata.selectedRpc);
						let signer = new ethers.Wallet(this.initdata.addressInfo.privateKey, provider);
						let address = signer.address
						let contract1 = new ethers.Contract(this.selectpairaddress, this.initdata
							.config.pairercabi,
							signer);
						let allowanceinfo = await contract1.allowance(address, this.initdata.config.swaprouter)
						let allowancenum = allowanceinfo.toString()
						if (Number(ethers.utils.parseUnits(this.lpnum, '18')) > Number(allowancenum)) {
							this.$ownerInstance.callMethod('hideloading')
							this.$ownerInstance.callMethod('openapprovewindow')
							return
						}
						let GasPrice = await provider.getGasPrice()
						let contract = new ethers.Contract(this.initdata.config.swaprouter, this.initdata
							.config
							.routerabi,
							signer);
						let timestamp = Date.now();
						let Gaslimit = await contract.estimateGas.removeLiquidityETH(
							this.selectcontract,
							ethers.utils.parseEther(String(this.lpnum)),
							1,
							1,
							address,
							timestamp + 60000)

						let data = await contract.populateTransaction.removeLiquidityETH(
							this.selectcontract,
							ethers.utils.parseEther(String(this.lpnum)),
							1,
							1,
							address,
							timestamp + 60000, {
								value: ethers.BigNumber.from("0"),
								gasPrice: GasPrice.toString(),
								gasLimit: Gaslimit.toString()
							})
						this.implementidinfo = data
						this.implementid = timestamp
						let res = {
							from: data.from,
							to: data.to,
							value: ethers.utils.formatUnits(data.value, "ether"),
							data: data.data,
							gasLimit: data.gasLimit.toString(),
							gasPrice: ethers.utils.formatUnits(data.gasPrice, "gwei"),
							fee: ethers.utils.formatUnits(data.gasLimit * data.gasPrice, "ether"),
							id: this.implementid
						}
						this.$ownerInstance.callMethod('openimplement', res)
					} catch (e) {
						this.$ownerInstance.callMethod('error', "合约执行失败")
						//TODO handle the exception
					}
					this.$ownerInstance.callMethod('hideloading')
				}

			},
			// 代币授权方法
			async shouquanover(newValue) {
				if (newValue) {
					this.$ownerInstance.callMethod('showloading')
					try {
						this.$ownerInstance.callMethod('changeapprovestatus', false)
						let provider = new ethers.providers.JsonRpcProvider(this.initdata.selectedRpc);
						let signer = new ethers.Wallet(this.initdata.addressInfo.privateKey, provider);
						let address = signer.address
						let GasPrice = await provider.getGasPrice()
						let contract = new ethers.Contract(this.selectpairaddress, this.initdata
							.config.erc20abi,
							signer);
						let Gaslimit = await contract.estimateGas.approve(this.initdata.config.swaprouter, this
							.initdata.config
							.approvenum)
						let data = await contract.populateTransaction.approve(this.initdata.config.swaprouter,
							this
							.initdata.config
							.approvenum, {
								value: ethers.BigNumber.from("0"),
								gasPrice: GasPrice.toString(),
								gasLimit: Gaslimit.toString()
							})
						this.implementidinfo = data
						this.implementid = Date.now()
						let res = {
							from: data.from,
							to: data.to,
							value: ethers.utils.formatUnits(data.value, "ether"),
							data: data.data,
							gasLimit: data.gasLimit.toString(),
							gasPrice: ethers.utils.formatUnits(data.gasPrice, "gwei"),
							fee: ethers.utils.formatUnits(data.gasLimit * data.gasPrice, "ether"),
							id: this.implementid,
							symbol: "LP",
							methond: "approve"
						}
						this.$ownerInstance.callMethod('openimplement', res)
					} catch (e) {
						this.$ownerInstance.callMethod('error', "合约执行失败")
					}
					this.$ownerInstance.callMethod('hideloading')
				}
			},
			// 去执行
			async implement(newValue) {
				if (newValue && newValue == this.implementid) {
					try {
						this.$ownerInstance.callMethod('showloading')
						let provider = new ethers.providers.JsonRpcProvider(this.initdata.selectedRpc);
						let signer = new ethers.Wallet(this.initdata.addressInfo.privateKey, provider);
						let res = await signer.sendTransaction(this.implementidinfo)
						let calldata = await provider.waitForTransaction(res.hash);
						if (calldata.status == 1) {
							this.$ownerInstance.callMethod("error", '交易请求成功')
						}
						this.getliquidity()
						this.lpnum = ""
						this.$ownerInstance.callMethod('hideloading')
					} catch (e) {
						this.$ownerInstance.callMethod('error', "合约执行失败")
					}
					this.$ownerInstance.callMethod('hideloading')
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	.page {
		width: 100vw;
		height: 100vh;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		background-color: #F7F7F7;

		.bigblock {
			flex: 1;

			overflow-y: scroll;

			.block1 {
				width: 686upx;
				margin: 0px auto;
				margin-top: 32upx;
				background-color: #fff;
				border-radius: 32upx;
				padding: 24upx 44upx;
				box-sizing: border-box;
				box-shadow: 0px 0px 2px rgba(0, 0, 0, .05);

				.line1 {
					display: flex;
					justify-content: center;

					.title {
						position: relative;

						.text1 {
							color: #000000;
							font-size: 32upx;
							font-weight: bold;
							position: relative;
							z-index: 10;
						}

						.bg {
							background: linear-gradient(180deg, #E7BCFF 0%, #B655EC 100%);
							width: 100%;
							height: 16upx;
							position: absolute;
							left: 0upx;
							bottom: -5upx;
							z-index: 1;

						}
					}


				}

				.line2 {
					margin-top: 32upx;
					font-size: 56upx;
					color: #000;
					text-align: center;
					font-weight: bold;
				}

				.line3 {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 40upx;

					.left {
						display: flex;
						align-items: center;

						.images {
							.image1 {
								width: 72upx;
							}

							.image2 {
								width: 72upx;
								position: relative;
								right: 20upx;
							}



						}

						.lines {

							// margin-left:16upx;
							.smallline1 {
								font-size: 28upx;
								color: #A135DD;
							}

							.smallline2 {
								font-size: 26upx;
								color: #4B3E58;
								margin-top: 4upx;
							}
						}
					}

					.right {
						.lines {
							.smallline1 {
								font-size: 24upx;
								color: #4B3E58;
								text-align: right;
							}

							.smallline2 {
								font-size: 36upx;
								color: #4B3E58;
								font-weight: bold;
								text-align: right;
								margin-top: 4upx;
							}
						}
					}
				}

				.line4 {
					margin-top: 40upx;

					.smallline1 {
						display: flex;
						justify-content: space-between;
						margin-top: 20upx;
						flex-wrap: wrap;

						.text1 {
							font-size: 28upx;
							color: #4B3E58;
						}

						.text2 {
							font-size: 32upx;
							color: #4B3E58;

							.smalltext {
								color: #931CD5;
								font-weight: bold;
							}
						}

					}


				}

				.line5 {
					background: linear-gradient(180deg, #C77BF1 0%, #931CD5 100%);
					width: 590upx;
					line-height: 80upx;
					color: #fff;
					border-radius: 16upx;
					text-align: center;
					margin: 0px auto;
					margin-top: 40upx;
				}

				.line6 {
					margin-top: 40upx;

					.button {
						width: 100%;
						line-height: 80upx;
						text-align: center;
						color: #fff;
						border-radius: 16upx;
						margin: 0upx auto;
					}

					.button:nth-child(1) {
						background-color: #FF760F;
					}

					.button:nth-child(2) {

						background: #03BAE8;
					}
				}
			}
		}



		.block2 {
			width: 686upx;
			padding: 48upx;
			border-radius: 32upx;
			background-color: #FFF;
			box-sizing: border-box;

			.line1 {
				font-size: 32upx;
				color: #4B3E58;
				text-align: center;
				font-weight: bold;
			}

			.line2 {
				display: flex;
				align-items: center;
				margin-top: 48upx;

				.input {
					flex: 1;
					background-color: #F7F7F7;
					// padding: 28upx 26upx;
					color: #000;
					font-size: 32upx;
					border-radius: 16upx;
				}

				.text1 {
					margin-left: 24upx;
					color: #4B3E58;
					font-size: 24upx;
					color: #4B3E58;
					font-weight: bold;
				}
			}

			.line3 {
				display: flex;
				justify-content: space-between;
				margin-top: 48upx;

				.text1 {
					width: 270upx;
					line-height: 80upx;
					background: #FFBC42 !important;
					text-align: center;
					border-radius: 16upx;
					color: #fff;
				}

				.text2 {
					width: 270upx;
					line-height: 80upx;
					text-align: center;
					border-radius: 16upx;
					color: #fff;
					background: linear-gradient(180deg, #A9E993 0%, #368321 100%);
				}
			}
		}

		.block3 {
			width: 686upx;
			padding: 32upx 56upx;
			border-radius: 48upx;
			box-sizing: border-box;
			background-color: #fff;

			.title {
				font-size: 48upx;
				color: #333333;
				text-align: center;
				border-bottom: 2upx solid #F7F7F7;
				padding-bottom: 32upx;
			}

			.line1 {
				font-size: 28upx;
				color: #545454;
				margin-top: 32upx;
			}

			.line2 {
				margin-top: 16upx;
				height: 96upx;

				.input {
					height: 96upx;
					width: 100%;


				}
			}

			.line3 {
				font-size: 32upx;
				color: #333;
				margin-top: 16upx;

				.tip {
					color: red;
				}
			}

			.line4 {
				width: 100%;
				display: flex;
				justify-content: space-between;

				.button {
					width: 271upx;
					height: 92upx;
					line-height: 92upx;
					border-radius: 64upx;
					text-align: center;
					color: #fff;
					margin-top: 48upx;
				}

				.button1 {
					background: #FFBC42 !important;
				}

				.button2 {

					background: linear-gradient(180deg, #A9E993 0%, #368321 100%);
				}
			}

		}
	}


	// 底部弹窗
	.popupTitle {
		text-align: center;
		position: relative;
		height: 110upx;
		line-height: 110upx;
		font-size: 36upx;
		border-bottom: 1upx solid #D8D8D8;

		.iconfont {
			position: absolute;
			right: 30upx;
		}
	}

	.numberBox {
		padding: 0 56upx;
		margin-top: 32upx;

		.number {
			width: 100%;
			text-align: center;
			font-size: 36upx;
			color: #3D3D3D;
			background: #F5F6F8;
			border-radius: 12upx;
			line-height: 96upx;
		}
	}

	.toAddress {
		margin-top: 0;
		border-top: 1upx solid #D8D8D8;
		border-bottom: 1upx solid #D8D8D8;
	}

	.fromAddress,
	.toAddress {
		padding: 54upx 54upx 52upx;
		font-size: 28upx;
		display: flex;

		.left {

			color: #999999;
			width: 152upx;
		}

		.right {
			flex: 1;

			.address {
				color: #3D3D3D;
				word-break: break-all;
			}

			.chain {
				color: #999999;
				font-size: 20upx;
			}
		}
	}

	.popupBtn {
		// background: red;
		padding: 30upx 40upx;
		display: flex;
		justify-content: space-between;

		.pbtn {
			font-size: 26upx;
			color: #F6F6F6;
			line-height: 88upx;
			background: linear-gradient(180deg, #A9E993 0%, #368321 100%);
			border-radius: 10upx;
			text-align: center;
			width: 46%;
		}

		.quxiaopth {
			background: #FFBC42 !important;
		}
	}

	.uni-form-item {
		width: 100%;

		.input-wrapper {
			display: flex;
			height: 70upx;
			background: #FFFFFF;
			padding: 0 20upx;
			border: 1upx solid #999999;
			align-items: center;
			border-radius: 10upx;

			.uni-input {
				flex: 1;
			}

			.icon {
				width: 32upx;
				height: 32upx;
			}
		}

		/deep/ .uni-easyinput__content-input {
			background-color: #fff !important;
		}
	}
</style>